iT邦幫忙

0

Day 27|程式碼重構(Refactoring)與 Git 版本控制

c#
  • 分享至 

  • xImage
  •  

今日學習目標

  • 理解 Refactoring 的用途
  • 認識重複程式碼與方法拆分
  • 在 TaskFlow 建立共用的驗證方法
  • 學會 git init、status、add、commit
  • 建立 .gitignore 避免追蹤資料庫與敏感設定
  • 使用 dotnet test 檢查修改後的功能

什麼是 Refactoring

Refactoring(重構)指的是:在不改變程式對外功能的前提下,改善內部程式碼的結構。

實作:將重複的驗證邏輯整理成方法

新增一個共用方法
在 TasksController 類別裡、ToDto() 方法上方,新增:

private string? ValidateTitle(string? title)
{
    if (string.IsNullOrWhiteSpace(title))
    {
        return "任務名稱不可空白";
    }

    string trimmedTitle = title.Trim();

    if (trimmedTitle.Length < 2 ||
        trimmedTitle.Length > 100)
    {
        return "任務名稱必須介於 2 到 100 個字元";
    }

    return null;
}

簡化 CreateTask()
在原本 CreateTask() 中,將檢查空白與長度的兩段 if,替換成:

string? error = ValidateTitle(input.Title);

if (error != null)
{
    ModelState.AddModelError(
        nameof(input.Title),
        error
    );

    return ValidationProblem(ModelState);
}

string title = input.Title.Trim();

簡化 UpdateTask()
同樣找到 UpdateTask() 裡檢查名稱的兩段 if,替換成:

string? error = ValidateTitle(input.Title);

if (error != null)
{
    ModelState.AddModelError(
        nameof(input.Title),
        error
    );

    return ValidationProblem(ModelState);
}

string title = input.Title.Trim();

後面原本的:

TaskItem task = await _taskService.CreateAsync(
    title,
    ownerId
);

與 CreatedAtAction() 都要保留。
簡化 UpdateTask()
同樣找到 UpdateTask() 裡檢查名稱的兩段 if,替換成:

string? error = ValidateTitle(input.Title);

if (error != null)
{
    ModelState.AddModelError(
        nameof(input.Title),
        error
    );

    return ValidationProblem(ModelState);
}

string title = input.Title.Trim();

後面原本的 taskService.UpdateAsync()、NotFound() 與 NoContent() 也全部保留。

認識 Git 版本控制

Git 是一種版本控制工具,可以記錄程式碼的變更。
Git 會將每次提交的版本記錄下來,方便日後比較修改內容。
Git 常用指令
https://ithelp.ithome.com.tw/upload/images/20261025/20184430w5brIEuNAT.png

安裝與檢查 Git

初始化 Git
在 TaskFlow3 目錄輸入:git init

建立 .gitignore

建立檔案
在 VS Code 左側的 TaskFlow3 根資料夾中新增:.gitignore
這些規則會讓 Git 忽略符合條件的檔案。
https://ithelp.ithome.com.tw/upload/images/20261025/20184430EAGmiMLE5b.pnghttps://ithelp.ithome.com.tw/upload/images/20261025/20184430p1jfplpTgm.png

建立第一個 Git 版本紀錄

查看 Git 狀態git status
設定提交者資訊

git config user.name "TaskFlow Student"
git config user.email "student@example.com"

加入檔案git add .
接著輸入:git status
再執行:git diff --cached --stat
建立 Commitgit commit -m "Day 27: Refactor task validation"
查看紀錄git log --oneline

確認重構沒有破壞程式

在終端機輸入:dotnet test .\TaskFlow3.Tests\TaskFlow3.Tests.csproj
可以啟動 API:dotnet run --project .\TaskFlow3.Api\TaskFlow3.Api.csproj


*提醒邦友,使用第三方服務/API 時,請務必評估資安風險與隱私保護
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言